package com.example.servicegateway.controller;

import com.example.servicegateway.filter.RateLimitFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关监控控制器
 * 
 * 功能说明：
 * 1. 提供网关运行状态监控接口
 * 2. 提供限流统计信息查询接口
 * 3. 提供路由配置查询接口
 * 4. 提供网关管理功能接口
 * 
 * @author Spring Cloud Demo
 * @version 1.0
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/api/gateway")
public class GatewayMonitorController {

    private static final Logger logger = LoggerFactory.getLogger(GatewayMonitorController.class);

    @Autowired
    private RateLimitFilter rateLimitFilter;

    @Autowired
    private RouteDefinitionLocator routeDefinitionLocator;

    /**
     * 获取网关健康状态
     * 
     * @return 网关健康状态信息
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> getHealth() {
        logger.info("🔍 查询网关健康状态");
        
        Map<String, Object> healthInfo = new HashMap<>();
        healthInfo.put("status", "UP");
        healthInfo.put("service", "Spring Cloud Gateway");
        healthInfo.put("timestamp", System.currentTimeMillis());
        healthInfo.put("version", "1.0.0");
        
        return ResponseEntity.ok(healthInfo);
    }

    /**
     * 获取限流统计信息
     * 
     * @return 限流统计信息
     */
    @GetMapping("/rate-limit/stats")
    public ResponseEntity<Map<String, Object>> getRateLimitStats() {
        logger.info("📊 查询限流统计信息");
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("stats", rateLimitFilter.getRateLimitStats());
        stats.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(stats);
    }

    /**
     * 获取路由配置信息
     * 
     * @return 路由配置信息
     */
    @GetMapping("/routes")
    public ResponseEntity<Map<String, Object>> getRoutes() {
        logger.info("🛣️ 查询路由配置信息");
        
        Map<String, Object> routesInfo = new HashMap<>();
        
        try {
            // 获取所有路由定义
            routeDefinitionLocator.getRouteDefinitions()
                    .collectList()
                    .subscribe(routes -> {
                        routesInfo.put("routes", routes);
                        routesInfo.put("count", routes.size());
                        
                        // 记录路由信息
                        routes.forEach(route -> {
                            logger.debug("路由: {} -> {}", route.getId(), route.getUri());
                        });
                    });
            
            routesInfo.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            logger.error("❌ 获取路由配置失败", e);
            routesInfo.put("error", "获取路由配置失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(routesInfo);
    }

    /**
     * 获取网关运行统计信息
     * 
     * @return 网关运行统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getGatewayStats() {
        logger.info("📈 查询网关运行统计信息");
        
        Map<String, Object> stats = new HashMap<>();
        
        // 系统信息
        Runtime runtime = Runtime.getRuntime();
        stats.put("system", Map.of(
                "totalMemory", runtime.totalMemory(),
                "freeMemory", runtime.freeMemory(),
                "usedMemory", runtime.totalMemory() - runtime.freeMemory(),
                "maxMemory", runtime.maxMemory(),
                "availableProcessors", runtime.availableProcessors()
        ));
        
        // 网关信息
        stats.put("gateway", Map.of(
                "serviceName", "service-gateway",
                "port", 8080,
                "startTime", System.currentTimeMillis()
        ));
        
        stats.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(stats);
    }

    /**
     * 刷新路由配置（可选功能）
     * 
     * @return 刷新结果
     */
    @PostMapping("/routes/refresh")
    public ResponseEntity<Map<String, Object>> refreshRoutes() {
        logger.info("🔄 刷新路由配置");
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "路由配置刷新成功");
        result.put("timestamp", System.currentTimeMillis());
        
        // 注意：这里需要实现具体的路由刷新逻辑
        // 可以通过发布事件或调用路由刷新服务来实现
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取网关配置信息
     * 
     * @return 网关配置信息
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getGatewayConfig() {
        logger.info("⚙️ 查询网关配置信息");
        
        Map<String, Object> config = new HashMap<>();
        
        // 路由配置
        config.put("routes", Map.of(
                "order-service", "/api/order/** -> service-order",
                "product-service", "/api/product/** -> service-product",
                "cart-service", "/api/cart/** -> service-product"
        ));
        
        // 过滤器配置
        config.put("filters", Map.of(
                "global-auth-filter", "全局认证过滤器",
                "rate-limit-filter", "限流过滤器",
                "cors-filter", "跨域过滤器"
        ));
        
        // 限流配置
        config.put("rateLimit", Map.of(
                "maxRequestsPerMinute", 100,
                "timeWindowMs", 60000
        ));
        
        config.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(config);
    }
} 